package com.cheetah.start.common.shoesImg;

import org.opencv.core.*;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgcodecs.Imgcodecs;

public class BackgroundRemoval {

    /**
     * 去除黄色背景，保留鞋子主体
     */
    public static Mat removeYellowBackground(Mat image) {
        Mat hsv = new Mat();
        Imgproc.cvtColor(image, hsv, Imgproc.COLOR_BGR2HSV);

        // 黄色背景的范围（根据您的实际情况调整）
        Scalar lowerYellow = new Scalar(20, 40, 40);
        Scalar upperYellow = new Scalar(35, 255, 255);

        Mat backgroundMask = new Mat();
        Core.inRange(hsv, lowerYellow, upperYellow, backgroundMask);

        // 反转掩码：背景变黑色，鞋子变白色
        Mat shoeMask = new Mat();
        Core.bitwise_not(backgroundMask, shoeMask);

        // 应用掩码到原图
        Mat result = new Mat();
        Core.bitwise_and(image, image, result, shoeMask);

        return result;
    }

    /**
     * 更精确的背景去除（处理边缘过渡）
     */
    public static Mat preciseBackgroundRemoval(Mat image) {
        Mat hsv = new Mat();
        Imgproc.cvtColor(image, hsv, Imgproc.COLOR_BGR2HSV);

        // 扩展黄色范围以捕捉边缘
        Scalar lowerYellow1 = new Scalar(15, 30, 30);
        Scalar upperYellow1 = new Scalar(25, 255, 255);
        Scalar lowerYellow2 = new Scalar(25, 30, 30);
        Scalar upperYellow2 = new Scalar(40, 255, 255);

        Mat mask1 = new Mat(), mask2 = new Mat();
        Core.inRange(hsv, lowerYellow1, upperYellow1, mask1);
        Core.inRange(hsv, lowerYellow2, upperYellow2, mask2);

        Mat backgroundMask = new Mat();
        Core.bitwise_or(mask1, mask2, backgroundMask);

        // 形态学操作平滑边界
        Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
        Imgproc.morphologyEx(backgroundMask, backgroundMask, Imgproc.MORPH_CLOSE, kernel);
        Imgproc.morphologyEx(backgroundMask, backgroundMask, Imgproc.MORPH_OPEN, kernel);

        // 反转并应用
        Mat shoeMask = new Mat();
        Core.bitwise_not(backgroundMask, shoeMask);

        Mat result = new Mat();
        Core.bitwise_and(image, image, result, shoeMask);

        return result;
    }
}
